# -*- coding: utf8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf8')

from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from bootcamp.market.models import Order, Goods, Shop
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template.loader import render_to_string
from django.core.context_processors import csrf
from django.core.mail import EmailMultiAlternatives
import json
from django.contrib.auth.decorators import login_required
from bootcamp.decorators import ajax_required

import smtplib
from email.mime.text import MIMEText
from_user="nqzx@nqzx.net"
ORDERS_PER_PAGE = 10

def send_mail(to_list,sub,content):
    if to_list and sub and content:
        e = EmailMultiAlternatives(sub, content, from_user, to_list)
        e.send()

def list_orders(request):
    if request.user.is_authenticated():
        hide_profile = False
    else:
        hide_profile = True
    user = request.user
    orders = Order.objects.filter(user=user)
    count = orders.count()
    return render(request, 'market/orders.html', {
        'orders': orders,
        'count': count,
        'hide_profile': hide_profile,
        })

def add_order(request):
    mobile = request.POST.get('mobile')
    shop_name = request.POST.get('shop')
    shop = Shop.objects.get(name=shop_name)
    goodstype = request.POST.get('goodstype')
    goodsweight = request.POST.get('goodsweight')
    addr = request.POST.get('addr')
    user = request.user
    order = Order()
    order.user = user
    order.shop = shop
    if shop.id == 1:
        order.content = "[手机：" + mobile + "]" + "[快件类型：" + goodstype + "]" + "[约重：" + goodsweight + "]" + "[取件地址：" + addr + "]"
    order.status = 0
    send_mail([shop.user.email], "您有新的订单，请登陆nqzx.net确认", order.content)
    order.save()
    return redirect('/market/list_orders/')

def delete_order(request):
    orderid = request.POST.get('orderid')
    orderid = int(orderid)
    order = Order.objects.get(pk=orderid)
    order.status = 3
    order.save()
    return redirect('/market/list_orders/')
